<template>
  <div class="fabric-inventory">
    <el-card class="filter-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="面料编号" prop="code">
          <el-input v-model="queryParams.code" placeholder="请输入面料编号" clearable />
        </el-form-item>
        <el-form-item label="面料名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入面料名称" clearable />
        </el-form-item>
        <el-form-item label="面料类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择面料类型" clearable>
            <el-option v-for="item in fabricTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="库存状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择库存状态" clearable>
            <el-option v-for="item in stockStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-container">
      <template #header>
        <div class="card-header">
          <span>面料库存列表</span>
          <div class="right-buttons">
            <el-button type="primary" @click="handleAdd">新增面料</el-button>
            <el-button type="success" @click="handleImport">导入库存</el-button>
            <el-button type="warning" @click="handleExport">导出库存</el-button>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="fabricList">
        <el-table-column type="index" width="50" label="序号" />
        <el-table-column prop="code" label="面料编号" min-width="120" />
        <el-table-column prop="name" label="面料名称" min-width="120" />
        <el-table-column prop="typeName" label="面料类型" min-width="100" />
        <el-table-column prop="color" label="颜色" min-width="80">
          <template #default="scope">
            <div class="color-block" :style="{ backgroundColor: scope.row.colorHex }"></div>
            {{ scope.row.color }}
          </template>
        </el-table-column>
        <el-table-column prop="specification" label="规格" min-width="100" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="currentStock" label="当前库存" width="100" sortable>
          <template #default="scope">
            <span :class="{ 'text-warning': scope.row.currentStock <= scope.row.minStock }">
              {{ scope.row.currentStock }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="minStock" label="最低库存" width="100" />
        <el-table-column prop="maxStock" label="最高库存" width="100" />
        <el-table-column label="库存状态" width="100">
          <template #default="scope">
            <el-tag :type="getStockStatusType(scope.row)">
              {{ getStockStatusText(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastPurchaseDate" label="最近采购日期" min-width="120" sortable />
        <el-table-column prop="supplierName" label="供应商" min-width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleView(scope.row)">查看</el-button>
            <el-button type="success" link @click="handleInOut(scope.row)">出入库</el-button>
            <el-button type="warning" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="pagination"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 面料详情对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form
        ref="fabricForm"
        :model="fabricForm"
        :rules="rules"
        label-width="100px"
        :disabled="dialogType === 'view'"
      >
        <el-form-item label="面料编号" prop="code">
          <el-input v-model="fabricForm.code" placeholder="请输入面料编号" />
        </el-form-item>
        <el-form-item label="面料名称" prop="name">
          <el-input v-model="fabricForm.name" placeholder="请输入面料名称" />
        </el-form-item>
        <el-form-item label="面料类型" prop="type">
          <el-select v-model="fabricForm.type" placeholder="请选择面料类型">
            <el-option v-for="item in fabricTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <el-input v-model="fabricForm.color" placeholder="请输入颜色名称" />
        </el-form-item>
        <el-form-item label="颜色代码" prop="colorHex">
          <el-color-picker v-model="fabricForm.colorHex" />
        </el-form-item>
        <el-form-item label="规格" prop="specification">
          <el-input v-model="fabricForm.specification" placeholder="请输入规格" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="fabricForm.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="当前库存" prop="currentStock">
          <el-input-number v-model="fabricForm.currentStock" :min="0" />
        </el-form-item>
        <el-form-item label="最低库存" prop="minStock">
          <el-input-number v-model="fabricForm.minStock" :min="0" />
        </el-form-item>
        <el-form-item label="最高库存" prop="maxStock">
          <el-input-number v-model="fabricForm.maxStock" :min="0" />
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId">
          <el-select v-model="fabricForm.supplierId" placeholder="请选择供应商">
            <el-option v-for="item in supplierOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="fabricForm.remark" type="textarea" rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button v-if="dialogType !== 'view'" type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 出入库对话框 -->
    <el-dialog v-model="inOutDialogVisible" title="出入库操作" width="500px">
      <el-form ref="inOutForm" :model="inOutForm" :rules="inOutRules" label-width="100px">
        <el-form-item label="面料信息">
          <div>{{ selectedFabric.name }} ({{ selectedFabric.code }})</div>
        </el-form-item>
        <el-form-item label="当前库存">
          {{ selectedFabric.currentStock }} {{ selectedFabric.unit }}
        </el-form-item>
        <el-form-item label="操作类型" prop="operationType">
          <el-radio-group v-model="inOutForm.operationType">
            <el-radio :label="1">入库</el-radio>
            <el-radio :label="2">出库</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="inOutForm.quantity" :min="1" />
        </el-form-item>
        <el-form-item label="操作原因" prop="reason">
          <el-select v-model="inOutForm.reason" placeholder="请选择操作原因">
            <el-option
              v-for="item in inOutForm.operationType === 1 ? inReasonOptions : outReasonOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="inOutForm.remark" type="textarea" rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="inOutDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitInOutForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDate } from '@/utils/index'

export default {
  name: 'FabricInventory',
  setup() {
    // 查询参数
    const queryParams = reactive({
      code: '',
      name: '',
      type: '',
      status: ''
    })

    // 面料列表数据
    const loading = ref(false)
    const fabricList = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)

    // 选项数据
    const fabricTypeOptions = [
      { value: 'cotton', label: '棉布' },
      { value: 'linen', label: '亚麻布' },
      { value: 'silk', label: '丝绸' },
      { value: 'wool', label: '羊毛' },
      { value: 'polyester', label: '涤纶' },
      { value: 'blend', label: '混纺' }
    ]

    const stockStatusOptions = [
      { value: 'normal', label: '正常' },
      { value: 'low', label: '偏低' },
      { value: 'high', label: '偏高' },
      { value: 'out', label: '缺货' }
    ]

    const supplierOptions = [
      { value: 1, label: '广州布料有限公司' },
      { value: 2, label: '深圳纺织厂' },
      { value: 3, label: '上海优质面料供应商' },
      { value: 4, label: '杭州丝绸厂' }
    ]

    const inReasonOptions = [
      { value: 'purchase', label: '采购入库' },
      { value: 'return', label: '退货入库' },
      { value: 'transfer', label: '调拨入库' },
      { value: 'other', label: '其他入库' }
    ]

    const outReasonOptions = [
      { value: 'production', label: '生产领用' },
      { value: 'transfer', label: '调拨出库' },
      { value: 'damage', label: '损耗报废' },
      { value: 'return', label: '退回供应商' },
      { value: 'other', label: '其他出库' }
    ]

    // 表单数据
    const dialogVisible = ref(false)
    const dialogType = ref('') // add, edit, view
    const fabricForm = reactive({
      id: null,
      code: '',
      name: '',
      type: '',
      color: '',
      colorHex: '#000000',
      specification: '',
      unit: '米',
      currentStock: 0,
      minStock: 10,
      maxStock: 1000,
      supplierId: '',
      remark: ''
    })

    // 表单校验规则
    const rules = {
      code: [
        { required: true, message: '请输入面料编号', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入面料名称', trigger: 'blur' }
      ],
      type: [
        { required: true, message: '请选择面料类型', trigger: 'change' }
      ],
      color: [
        { required: true, message: '请输入颜色名称', trigger: 'blur' }
      ],
      colorHex: [
        { required: true, message: '请选择颜色代码', trigger: 'change' }
      ],
      unit: [
        { required: true, message: '请输入单位', trigger: 'blur' }
      ],
      supplierId: [
        { required: true, message: '请选择供应商', trigger: 'change' }
      ]
    }

    // 出入库对话框数据
    const inOutDialogVisible = ref(false)
    const selectedFabric = ref({})
    const inOutForm = reactive({
      operationType: 1, // 1-入库, 2-出库
      quantity: 1,
      reason: '',
      remark: ''
    })

    const inOutRules = {
      operationType: [
        { required: true, message: '请选择操作类型', trigger: 'change' }
      ],
      quantity: [
        { required: true, message: '请输入数量', trigger: 'blur' },
        { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
      ],
      reason: [
        { required: true, message: '请选择操作原因', trigger: 'change' }
      ]
    }

    // 计算属性
    const dialogTitle = computed(() => {
      return {
        add: '新增面料',
        edit: '编辑面料',
        view: '面料详情'
      }[dialogType.value]
    })

    // 方法
    const fetchData = () => {
      loading.value = true
      // TODO: 这里需要调用实际API获取面料库存列表
      loading.value = false
    }

    const handleQuery = () => {
      currentPage.value = 1
      fetchData()
    }

    const resetQuery = () => {
      Object.keys(queryParams).forEach(key => {
        queryParams[key] = ''
      })
      handleQuery()
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      fetchData()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchData()
    }

    const resetForm = () => {
      Object.assign(fabricForm, {
        id: null,
        code: '',
        name: '',
        type: '',
        color: '',
        colorHex: '#000000',
        specification: '',
        unit: '米',
        currentStock: 0,
        minStock: 10,
        maxStock: 1000,
        supplierId: '',
        remark: ''
      })
    }

    const handleAdd = () => {
      resetForm()
      dialogType.value = 'add'
      dialogVisible.value = true
    }

    const handleView = (row) => {
      Object.assign(fabricForm, row)
      dialogType.value = 'view'
      dialogVisible.value = true
    }

    const handleEdit = (row) => {
      Object.assign(fabricForm, row)
      dialogType.value = 'edit'
      dialogVisible.value = true
    }

    const handleDelete = (row) => {
      ElMessageBox.confirm(`确定要删除面料"${row.name}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // TODO: 这里需要调用实际API删除面料
        ElMessage.success('删除成功')
        fetchData()
      }).catch(() => {})
    }

    const submitForm = () => {
      // TODO: 这里需要调用实际API保存面料数据
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功')
      dialogVisible.value = false
      fetchData()
    }

    const handleInOut = (row) => {
      selectedFabric.value = row
      inOutForm.operationType = 1
      inOutForm.quantity = 1
      inOutForm.reason = ''
      inOutForm.remark = ''
      inOutDialogVisible.value = true
    }

    const submitInOutForm = () => {
      // TODO: 这里需要调用实际API提交出入库记录
      const operationText = inOutForm.operationType === 1 ? '入库' : '出库'
      ElMessage.success(`${operationText}操作成功`)
      inOutDialogVisible.value = false
      fetchData()
    }

    const getStockStatusType = (row) => {
      if (row.currentStock <= 0) return 'danger'
      if (row.currentStock <= row.minStock) return 'warning'
      if (row.currentStock >= row.maxStock) return ''
      return 'success'
    }

    const getStockStatusText = (row) => {
      if (row.currentStock <= 0) return '缺货'
      if (row.currentStock <= row.minStock) return '偏低'
      if (row.currentStock >= row.maxStock) return '偏高'
      return '正常'
    }

    const handleImport = () => {
      ElMessage.info('导入功能开发中...')
    }

    const handleExport = () => {
      ElMessage.info('导出功能开发中...')
    }

    onMounted(() => {
      fetchData()
    })

    return {
      // 数据
      queryParams,
      loading,
      fabricList,
      currentPage,
      pageSize,
      total,
      fabricTypeOptions,
      stockStatusOptions,
      supplierOptions,
      dialogVisible,
      dialogType,
      dialogTitle,
      fabricForm,
      rules,
      inOutDialogVisible,
      selectedFabric,
      inOutForm,
      inOutRules,
      inReasonOptions,
      outReasonOptions,

      // 方法
      handleQuery,
      resetQuery,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleView,
      handleEdit,
      handleDelete,
      submitForm,
      handleInOut,
      submitInOutForm,
      getStockStatusType,
      getStockStatusText,
      handleImport,
      handleExport
    }
  }
}
</script>

<style scoped>
.fabric-inventory {
  padding: 10px;
}

.filter-container {
  margin-bottom: 20px;
}

.table-container {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right-buttons {
  display: flex;
  gap: 10px;
}

.color-block {
  display: inline-block;
  width: 16px;
  height: 16px;
  border-radius: 2px;
  margin-right: 5px;
  border: 1px solid #ddd;
  vertical-align: middle;
}

.text-warning {
  color: #e6a23c;
  font-weight: bold;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 